<?php

namespace app\admin\controller\merchant;
/**
 *  @icon fa fa-ads
 **/
class Ads extends Base
{

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = loadModel('tyyh\\Ads');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $search = $this->request->param('search');
            if($search) {
                $where = [
                    'id|image|url' => ['like', "%" . $search . '%']
                ];
            }
            $list = $this->model
                ->append(['status_text', 'type_text'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $this->assign_type_list();
        $this->assign_status_list();
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');
            $this->model->save($row);
            $this->success();
        }
        $this->assign_type_list();
        $this->assign_status_list();
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');
            $this->model->save($row, ['id' => $ids]);
            $this->success();
        }
        $row = $this->model->where(['id' => $ids])->find();
        $this->assign_type_list($row['type']);
        $this->assign_status_list($row['status']);
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    protected function assign_type_list($type = '') {
        $typeList = loadEnum('AdsType')->get_options();
        $typeListJson = json_encode_cn($typeList);
        $this->assign('typeListJson', $typeListJson);
        $typeList = build_select('row[type]', $typeList, $type, ['class' => 'form-control selectpicker']);
        $this->assign('typeList', $typeList);
    }

    protected function assign_status_list($status = '') {
        $statusList = loadEnum('Status')->get_show_options();
        $statusListJson = json_encode_cn($statusList);
        $this->assign('statusListJson', $statusListJson);
        $statusList = build_select('row[status]', $statusList, $status, ['class' => 'form-control selectpicker']);
        $this->assign('statusList', $statusList);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $this->model->where(['id' => ['in', $ids]])->delete();
        $this->success();
    }

}
